package com.zzk.audiovideodemo.videoview;

import android.app.Service;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zzk.audiovideodemo.MainActivity;
import com.zzk.audiovideodemo.R;

import java.lang.reflect.Field;

/**
 * @ProjectName: AudioVideoDemo
 * @Package: com.zzk.audiovideodemo.videoview
 * @ClassName: VideoViewActivity
 * @Description:
 * @Author: brilliantzhao
 * @CreateDate: 2021.3.23 14:08
 * @UpdateUser:
 * @UpdateDate: 2021.3.23 14:08
 * @UpdateRemark:
 * @Version: 1.0.0
 */

public class VideoViewActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private VideoView vvMain;
    /**
     * 动态视频的存放地址
     */
    private String mDynamicVideo;
    /**
     * 静态视频的存放地址
     */
    private String mStaticVideo;
    private MediaPlayer mMediaPlayer;
    private TextView tvInfo;
    private int mCurrentVolume = 100;
    private boolean isFirst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videoview);
        initView();
        initData();
        setListeners();
        setData();
    }

    private void initView() {
        vvMain = findViewById(R.id.vv_main);
        tvInfo = findViewById(R.id.tv_info);
    }

    private void initData() {
//        mDynamicVideo = PathUtils.getExternalMoviesPath()+"/shupin.mp4";
        mDynamicVideo = PathUtils.getExternalMoviesPath() + "/dync.mp4";
        //static
        mStaticVideo = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/shupin.mp4";
        PermissionUtils.permission(
                PermissionConstants.STORAGE
        ).request();
        //此处的context一定要传入activity,不然会崩溃的程序，因为没有windows
        // android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        MediaController mediaController = new MediaController(this);
        mediaController.setPrevNextListeners(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一首,实现具体的切换逻辑
                ToastUtils.showShort("点击了下一首");
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一首，实现具体的切换逻辑
                ToastUtils.showShort("点击了上一首");
            }
        });
        vvMain.setMediaController(mediaController);
        vvMain.setZOrderOnTop(true);
    }

    private void setData() {
//        vvMain.setVideoPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)+"/dync.mp4");
//        vvMain.setVideoPath("http://vfx.mtime.cn/Video/2019/07/12/mp4/190712140656051701.mp4");
        vvMain.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video_test));
        vvMain.requestFocus();
//       vvMain.setBackgroundColor(getResources().getColor(R.color.white_full));
//       vvMain.start();
    }

    private void setListeners() {
        vvMain.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                LogUtils.dTag(TAG, "视频准备ok", "width=" + mp.getVideoWidth(), "height=" + mp.getVideoHeight());
                LogUtils.dTag(TAG, "控件宽=" + vvMain.getWidth() + ",高=" + vvMain.getHeight());
                mp.start();
            }
        });
        vvMain.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mp.isLooping()) {
                    LogUtils.dTag(TAG, "视频循环播放!");
                } else {
                    mMediaPlayer = null;
                }
                if (isFirst) {
                    vvMain.setVideoPath(mStaticVideo);
                    isFirst = false;
                } else {
                    vvMain.setVideoPath(mDynamicVideo);
                    isFirst = true;
                }
                vvMain.start();
                LogUtils.dTag(TAG, "视频播放完毕");

//                mp.start();
                //调用start也可以
                //调用resume方法亦可重复播放
//                vvMain.resume();
            }
        });
        vvMain.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.dTag(TAG, "视频播放异常", "what=" + what, "extra=" + extra);
                mMediaPlayer = null;
//                vvMain.stopPlayback();
                //返回值设置为false,依然会弹窗提示错误，返回值为true,则不会弹，但也不会再调用onCompletion
                return true;
            }
        });
        vvMain.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                //视频需要缓冲
                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    //显示缓冲提示
                    ToastUtils.showShort("视频缓冲中...");
                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    //视频缓冲完毕
                    ToastUtils.showShort("视频缓冲完毕...");
                }
                mMediaPlayer = null;
                mMediaPlayer = mp;
                LogUtils.dTag(TAG, "视频播放INFO", "what=" + what, "extra=" + extra);
                return false;
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        vvMain.stopPlayback();
        mMediaPlayer = null;
//        if(vvMain.canPause()){
//            vvMain.pause();
//        }
        LogUtils.dTag(TAG, "触发pause");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        vvMain.resume();
        LogUtils.dTag(TAG, "触发restart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.dTag(TAG, "触发onResume");
//        vvMain.resume();
//        vvMain.start();
    }

    public void getState(View view) {
        String state = vvMain.isPlaying() ? "播放中" : "未播放!";
        LogUtils.dTag(TAG, state);
        ToastUtils.showLong(state);
    }

    public void stop(View view) {
        vvMain.stopPlayback();
//        vvMain.suspend();
    }

    public void pause(View view) {
        vvMain.pause();
    }

    public void play(View view) {
        vvMain.start();
    }

    public void resume(View view) {
        vvMain.resume();
    }

    public void suspend(View view) {
        vvMain.suspend();
    }

    public void position(View view) {
        if (!vvMain.isPlaying()) {
            ToastUtils.showShort("视频未播放");
            return;
        }
        String info = "total=" + vvMain.getDuration() + "\npos=" + vvMain.getCurrentPosition();
        tvInfo.setText(info);
    }

    public void buffer(View view) {
        if (!vvMain.isPlaying()) {
            ToastUtils.showShort("视频未播放");
            return;
        }
        String percent = "缓冲进度=" + vvMain.getBufferPercentage();
        tvInfo.setText(percent);
    }

    public void increase(View view) {
        //通过audioManager设置全局音量
//        increaseByAudioManager();
        //通过持有回调中的对象设置音量
//        increaseByMediaPlayer();
        //通过反射获取对象设置音量
        increaseByReflect();
    }

    public void decrease(View view) {
//        decreaseByAudioManager();
//        decreaseByMediaPlayer();

        decreaseByReflect();
    }

    private void decreaseByAudioManager() {
        AudioManager audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        int beforeVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER,
                AudioManager.FLAG_PLAY_SOUND);
        int afterVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.dTag(TAG, "设置前=" + beforeVolume + ",设置后=" + afterVolume);
    }

    private void decreaseByMediaPlayer() {
        if (mMediaPlayer != null && vvMain.isPlaying()) {
            if (mCurrentVolume == 0) {
                return;
            }
            mCurrentVolume -= 10;
            mMediaPlayer.setVolume(mCurrentVolume / 100F, mCurrentVolume / 100F);
            LogUtils.dTag(TAG, "当前音量=" + mCurrentVolume / 100F);
        }
    }

    private void decreaseByReflect() {
        long beforeTime = System.currentTimeMillis();
        MediaPlayer mediaPlayer = getReflectMediaPlayer();
        LogUtils.dTag(TAG, "反射获取对象时间:" + (System.currentTimeMillis() - beforeTime));
        if (mediaPlayer != null && vvMain.isPlaying()) {
            if (mCurrentVolume == 0) {
                return;
            }
            mCurrentVolume -= 10;
            mediaPlayer.setVolume(mCurrentVolume / 100F, mCurrentVolume / 100F);
            LogUtils.dTag(TAG, "当前音量=" + mCurrentVolume / 100F);
        }
    }


    private void increaseByAudioManager() {
        AudioManager audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        int beforeVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,
                AudioManager.FLAG_PLAY_SOUND);
        int afterVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.dTag(TAG, "设置前=" + beforeVolume + ",设置后=" + afterVolume);
    }

    private void increaseByMediaPlayer() {
        if (mMediaPlayer != null && vvMain.isPlaying()) {
            if (mCurrentVolume == 100) {
                return;
            }
            mCurrentVolume += 10;
            mMediaPlayer.setVolume(mCurrentVolume / 100F, mCurrentVolume / 100F);
            LogUtils.dTag(TAG, "当前音量=" + mCurrentVolume / 100F);
        }
    }

    private void increaseByReflect() {
        MediaPlayer mediaPlayer = getReflectMediaPlayer();
        if (mediaPlayer != null && vvMain.isPlaying()) {
            if (mCurrentVolume == 100) {
                return;
            }
            mCurrentVolume += 10;
            mediaPlayer.setVolume(mCurrentVolume / 100F, mCurrentVolume / 100F);
            LogUtils.dTag(TAG, "当前音量=" + mCurrentVolume / 100F);
        }
    }


    public void mute(View view) {
//        AudioManager audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
//        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//        int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//        LogUtils.dTag(TAG, "最大音量=" + maxVolume + ",当前音量=" + curVolume);
//        if (curVolume != maxVolume) {
//            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_PLAY_SOUND);
//        } else {
//            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);
//        }
        if (mMediaPlayer != null && vvMain.isPlaying()) {
            mMediaPlayer.setVolume(0, 1);
            ToastUtils.showShort("设置静音!");
        }
    }

    public void restoreVolume(View view) {
        if (mMediaPlayer != null && vvMain.isPlaying()) {
            mMediaPlayer.setVolume(1, 0);
            ToastUtils.showShort("恢复音量!");
        }
    }

    private MediaPlayer getReflectMediaPlayer() {
        try {
            Class clazz = Class.forName("android.widget.VideoView");
            Field field = clazz.getDeclaredField("mMediaPlayer");
            field.setAccessible(true);
            return (MediaPlayer) field.get(vvMain);
        } catch (Exception e) {
            LogUtils.eTag(TAG, "反射错误:" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}